Dictionaries

Dictionary is a set of key-value pair, where value is any hashable object. As Lists are indexed by integers, Dictionries are indexed by keys.

Creating a Dictionaries

  • Creating an Empty Dictionary

    x = {}      # {} denotes dictionary type (not set)
    x = dict()
    
  • Creating Dictionary with initial values

    x = {'eight':8,'nine':9}
    
In [1]:
x = {'eight':8,'nine':9}
In [2]:
x['eight']
Out[2]:
8
In [3]:
x[0]
--------------------------------------------------------------------------
KeyError                                 Traceback (most recent call last)
<ipython-input-3-1ae75c28907a> in <module>()
----> 1 x[0]

KeyError: 0

If a key is not present in Dictionary, KeyError is raised

In [4]:
x['zero'] = 0 # Adding a key-value to dictionary
x
Out[4]:
{'eight': 8, 'nine': 9, 'zero': 0}
In [5]:
del x['nine']  # Deleting based on key
x
Out[5]:
{'eight': 8, 'zero': 0}
In [6]:
'zero' in x    # Only key membership can be checked
Out[6]:
True

Dictionary Methods

If d is a dictionary

  • d.keys() returns a view of d’s keys
  • d.values() returns a view of d’s values
  • d.items() returns a view of d’s key-value pairs
In [7]:
x
Out[7]:
{'eight': 8, 'zero': 0}
In [8]:
x.keys()
Out[8]:
dict_keys(['eight', 'zero'])
In [11]:
x.values()
Out[11]:
dict_values([8, 0])
In [12]:
x.items()
Out[12]:
dict_items([('eight', 8), ('zero', 0)])
In [13]:
for k,v in x.items():
    print("{}={}".format(k,v))
eight=8
zero=0

Dictionary Values can be any hashable object. This means they can be lists, tuples,… . Using Dictionaries, one can implement an Adjacency List Representation of Graph Data Structure.